package ui.view;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.MalformedURLException;
import java.net.URL;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.SwingConstants;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import net.sf.saxon.s9api.SaxonApiException;

import org.jdesktop.jdic.browser.WebBrowser;
import org.jdesktop.jdic.browser.WebBrowserEvent;
import org.jdesktop.jdic.browser.WebBrowserListener;

import ui.Utility;
import ui.frame.InfiniteProgressPanel;

import static constants.GTextbookConstants.*;

public class ShowFrame extends JFrame{

	
	public ShowFrame(){
		super();
		/*
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {}
*/


        Browser browserPanel = new Browser(this);

        this.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
            }
        });

 		
		
		 browser = browserPanel.webBrowser;
	     Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
	     // setBounds(0,0,size.width/2,size.height/2);
	      JPanel panel = new JPanel();
	      panel.setLayout(new GridLayout(1, 1));
	      panel.setPreferredSize(new Dimension(700,599));
	      panel.add(browserPanel);

	      getContentPane().add(panel, BorderLayout.CENTER);
	      pack();
	      setVisible(false);


	}
	
	public ShowFrame(String engTitle, String chiTitle, int language){
      this();
	  if(language == English){
		  setTitle(engTitle);
	  }
	  if(language == Chinese){
		  setTitle(chiTitle);
	  }
	}
	  public ShowFrame(NodeInfo content){
		  this();
		  setTitle(content.toString());
	  }
	  
	  public ShowFrame(String url){
		  this();
		  if(url!=null && url != ""){
				show(url);
		  }
	  }
	  
	  public ShowFrame(String url, String engTitle, String chiTitle, int language){
		  this(url);
		  if(language == English){
			  setTitle(engTitle);
		  }
		  if(language == Chinese){
			  setTitle(chiTitle);
		  }
		  
	  }
	
	  
	  
	  class WindowHandler extends WindowAdapter {
		    // Handler for window closing event
		    public void windowClosing(WindowEvent e) {
		    }
	  }
	  
	  
	  public void show(String source, String xsl, String output){
    	  	try {
    	  		if(source!=null&&xsl!=null){
    	  			Utility.transformation(source, xsl, output, "xml");
    	  		}
      	  	} catch (SaxonApiException e1) {
      		  // TODO Auto-generated catch block
      		  e1.printStackTrace();
      		  //browser.setURL();
      		  return;
      	  	}
	
      	  	try {

  	      		browser.setURL(new URL("file:///"+output));
      	  	} catch (MalformedURLException h) {
      		  System.out.println(h.getMessage());
      		  return;
      	  	} 
		  
		  
		  //Thread performer = new Thread(new contentWaiterForEGT(this,source,xsl,output), "Performer");
          //performer.start();
		  
	  }
	  
	  /*
	  public class contentWaiterForEGT implements Runnable{

		  public contentWaiterForEGT(JFrame frame, String source, String xslPath, String output){
			  this.source = source;
			  this.xsl = xslPath;
			  this.output = output;
		      frame.getContentPane().add(buildInfinitePanel());
		  }
		  
		  
		  public void run() {
			// TODO Auto-generated method stub
			glassPane.start();
			try {
          	  	try {
          	  		Utility.transformation(source, xsl, output);
          	  	} catch (SaxonApiException e1) {
          		  // TODO Auto-generated catch block
          		  e1.printStackTrace();
          		  //browser.setURL();
          		  return;
          	  	}
		
          	  	try {

      	      		//browser.setURL(new URL("file:///"+output));
          	  		browser.setURL(new URL("http://java.net"));
          	  	} catch (MalformedURLException h) {
          		  System.out.println(h.getMessage());
          		  return;
          	  	} 
            } //catch (InterruptedException ie) { }
            finally{
            	 glassPane.stop();
            }
		}
		
        private String source;
        private String xsl;
        private String output;
		
		  
	  }
	  
	  
	  class contentWaiterForMathDox implements Runnable{
		  
		  public contentWaiterForMathDox(JFrame frame, String output){
			  this.output = output;
		      frame.getContentPane().add(buildInfinitePanel());
		  }
		  
		  
		  
		  private String output;



		public void run() {
			// TODO Auto-generated method stub
			
			try {
          	  	try {
					if(output!=null && output!=""){
						browser.setURL(new URL(output));	
					}
          	  	} catch (MalformedURLException h) {
          		  System.out.println(h.getMessage());
          		  return;
          	  	} 
			}    //catch (InterruptedException ie) { }
        	finally{
        		glassPane.stop();
        	}
		}
	  }

*/
	  public void show(String output){
		  
    	  	try {
				if(output!=null && output!=""){
					browser.setURL(new URL(output));	
				}
      	  	} catch (MalformedURLException h) {
      		  System.out.println(h.getMessage());
      		  return;
      	  	} 
		  
		  
		 // glassPane.start();
		  
		  
         // Thread performer = new Thread(new contentWaiterForMathDox(this,output), "Performer");
          
          
         // performer.start();
		  
	  }
	  
	  public Container buildInfinitePanel() {
	      JPanel pane = new JPanel(new BorderLayout());
	      glassPane = new InfiniteProgressPanel();
	      setGlassPane(glassPane);
	      return pane;
	  }
	
	private WebBrowser browser;
	private InfiniteProgressPanel glassPane;

	public WebBrowser getBrowser() {
		return browser;
	}
	public void setBrowser(WebBrowser browser) {
		this.browser = browser;
	}
	
	
	
	public class Browser extends JPanel {
	    public ImageIcon browseIcon = new ImageIcon(RESOURCE_DIRECTORY+"/presentation/images/Right.gif");

	    BorderLayout borderLayout1 = new BorderLayout();

	    JToolBar jBrowserToolBar = new JToolBar();
	    JButton jStopButton = new JButton("Stopp",new ImageIcon(RESOURCE_DIRECTORY+"/presentation/images/Stop.png"));
	            //new ImageIcon(getClass().getResource("images/Stop.png")));

	    JButton jRefreshButton = new JButton("Refresh",
	            new ImageIcon(RESOURCE_DIRECTORY+"/presentation/images/Reload.png"));
	    JButton jForwardButton = new JButton("Forward",
	            new ImageIcon(RESOURCE_DIRECTORY+"/presentation/images/Forward.png"));
	    JButton jBackButton = new JButton("Back",
	            new ImageIcon(RESOURCE_DIRECTORY+"/presentation/images/Back.png"));

	    JPanel jAddressPanel = new JPanel();
	    JLabel jAddressLabel = new JLabel();
	    JTextField jAddressTextField = new JTextField();
	    JButton jGoButton = new JButton();
	    JPanel jAddrToolBarPanel = new JPanel();
	    MyStatusBar statusBar = new MyStatusBar();
	    JPanel jBrowserPanel = new JPanel();

	    WebBrowser webBrowser;

	    public Browser(JFrame frame) {
	    	this.frame=frame;
	        try {
	            jbInit();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

	    private JFrame frame;

	    private void jbInit() throws Exception {
	        this.setLayout(borderLayout1);

	        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

	        this.setPreferredSize(new Dimension(screenSize.width * 9 / 10,
	                screenSize.height * 8 / 10));

	        ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);

	        jAddressLabel.setBorder(BorderFactory.createEmptyBorder(0, 4, 0, 4));
	        jAddressLabel.setToolTipText("");
	        jAddressLabel.setText(" URL: ");

	        jGoButton.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(0,
	                2, 0, 2),
	                new EtchedBorder()));
	        jGoButton.setMaximumSize(new Dimension(60, 25));
	        jGoButton.setMinimumSize(new Dimension(60, 25));
	        jGoButton.setPreferredSize(new Dimension(60, 25));
	        jGoButton.setToolTipText("Load the given URL");
	        jGoButton.setIcon(browseIcon);
	        jGoButton.setText("GO");
	        jGoButton.addActionListener(new Browser_jGoButton_actionAdapter(this));
	        jAddressPanel.setLayout(new BorderLayout());

	        jAddressTextField.addActionListener(new Browser_jAddressTextField_actionAdapter(this));
	        jBackButton.setToolTipText("Go back one page");
	        jBackButton.setHorizontalTextPosition(SwingConstants.TRAILING);
	        jBackButton.setEnabled(false);
	        jBackButton.setMaximumSize(new Dimension(75, 27));
	        jBackButton.setPreferredSize(new Dimension(75, 27));
	        jBackButton.addActionListener(new Browser_jBackButton_actionAdapter(this));
	        jForwardButton.setToolTipText("Go forward one page");
	        jForwardButton.setEnabled(false);
	        jForwardButton.setMaximumSize(new Dimension(85, 27));
	        jForwardButton.setMinimumSize(new Dimension(85, 27));
	        jForwardButton.setPreferredSize(new Dimension(85, 27));
	        jForwardButton.addActionListener(new Browser_jForwardButton_actionAdapter(this));
	        jRefreshButton.setToolTipText("Reload current page");
	        jRefreshButton.setEnabled(true);
	        jRefreshButton.setMaximumSize(new Dimension(85, 27));
	        jRefreshButton.setMinimumSize(new Dimension(85, 27));
	        jRefreshButton.setPreferredSize(new Dimension(85, 27));
	        jRefreshButton.addActionListener(new Browser_jRefreshButton_actionAdapter(this));
	        jStopButton.setToolTipText("Stop loading this page");
	        jStopButton.setVerifyInputWhenFocusTarget(true);
	        jStopButton.setText("Stop");
	        jStopButton.setEnabled(true);
	        jStopButton.setMaximumSize(new Dimension(75, 27));
	        jStopButton.setMinimumSize(new Dimension(75, 27));
	        jStopButton.setPreferredSize(new Dimension(75, 27));
	        jStopButton.addActionListener(new Browser_jStopButton_actionAdapter(this));
	        jAddressPanel.add(jAddressLabel, BorderLayout.WEST);
	        jAddressPanel.add(jAddressTextField, BorderLayout.CENTER);
	        jAddressPanel.add(jGoButton, BorderLayout.EAST);
	        jAddressPanel.setBorder(BorderFactory.createCompoundBorder(
	            BorderFactory.createEtchedBorder(),
	            BorderFactory.createEmptyBorder(2, 0, 2, 0)));

	        jBrowserToolBar.setFloatable(false);
	        jBrowserToolBar.add(jBackButton, null);
	        jBrowserToolBar.add(jForwardButton, null);
	        jBrowserToolBar.addSeparator();
	        jBrowserToolBar.add(jRefreshButton, null);
	        jBrowserToolBar.add(jStopButton, null);
	        jBrowserToolBar.setBorder(BorderFactory.createCompoundBorder(
	            BorderFactory.createEtchedBorder(),
	            BorderFactory.createEmptyBorder(2, 2, 2, 0)));

	        jAddrToolBarPanel.setLayout(new BorderLayout());
	        jAddrToolBarPanel.add(jAddressPanel, BorderLayout.CENTER);
	        jAddrToolBarPanel.add(jBrowserToolBar, BorderLayout.WEST);
	        jAddrToolBarPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 2, 0));

	        statusBar.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
	        //statusBar.lblDesc.setText(frame.getTitle());

	        webBrowser = new WebBrowser();
			// Print out debug messages in the command line.
			//webBrowser.setDebug(true);

	        webBrowser.addWebBrowserListener(new WebBrowserListener() {
	            public void downloadStarted(WebBrowserEvent event) {
	                updateStatusInfo("Loading started.");
	            }

	            public void downloadCompleted(WebBrowserEvent event) {
	                jBackButton.setEnabled(webBrowser.isBackEnabled());
	                jForwardButton.setEnabled(webBrowser.isForwardEnabled());

	                updateStatusInfo("Loading completed.");

	                URL currentUrl = webBrowser.getURL();

	                if (currentUrl != null) {
	                    jAddressTextField.setText(currentUrl.toString());
	                }
	            }

	            public void downloadProgress(WebBrowserEvent event) {
	                // updateStatusInfo("Loading in progress...");
	            }

	            public void downloadError(WebBrowserEvent event) {
	                updateStatusInfo("Loading error.");
	            }

	            public void documentCompleted(WebBrowserEvent event) {
	                updateStatusInfo("Document loading completed.");
	            }

	            public void titleChange(WebBrowserEvent event) {
	                updateStatusInfo("Title of the browser window changed.");
	            }  

	            public void statusTextChange(WebBrowserEvent event) {
	                 updateStatusInfo("Status text changed.");
	            } 
	            public void windowClose(WebBrowserEvent event) {
	               /* updateStatusInfo("Closed by script.");
	                if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(
	                    webBrowser,
	                    "The webpage you are viewing is trying to close the window.\n Do you want to close this window?",
	                    "Warning",
	                    JOptionPane.YES_NO_OPTION,
	                    JOptionPane.QUESTION_MESSAGE))
	                {
	                     System.exit(0);
	                }*/
	            }
	        });

	        jBrowserPanel.setLayout(new BorderLayout());
	        jBrowserPanel.add(webBrowser, BorderLayout.CENTER);

	        this.add(jAddrToolBarPanel, BorderLayout.NORTH);
	        this.add(statusBar, BorderLayout.SOUTH);
	        this.add(jBrowserPanel, BorderLayout.CENTER);
	    }

	    void updateStatusInfo(String statusMessage) {
	        statusBar.lblStatus.setText(statusMessage);
	    }

	    /**
	     * Check the current input URL string in the address text field, load it,
	     * and update the status info and toolbar info.
	     */
	    void loadURL() {
	        String inputValue = jAddressTextField.getText();

	        if (inputValue == null) {
	            JOptionPane.showMessageDialog(this, "The given URL is NULL:",
	                    "Warning", JOptionPane.WARNING_MESSAGE);
	        } else {
	            // Check if the text value is a URL string.
	            URL curUrl = null;

	            try {
	                // Check if the input string is a local path by checking if it starts
	                // with a driver name(on Windows) or root path(on Unix).               
	                File[] roots = File.listRoots();

	                for (int i = 0; i < roots.length; i++) {
	                    if (inputValue.toLowerCase().startsWith(roots[i].toString().toLowerCase())) {
	                        File curLocalFile = new File(inputValue);

	                        curUrl = curLocalFile.toURL();
	                        break;
	                    }
	                }

	                if (curUrl == null) {
	                    // Check if the text value is a valid URL.
	                    try {
	                        curUrl = new URL(inputValue);
	                    } catch (MalformedURLException e) {
	                            if (inputValue.toLowerCase().startsWith("ftp.")) {
	                                curUrl = new URL("ftp://" + inputValue);
	                            } else if (inputValue.toLowerCase().startsWith("gopher.")) {
	                                curUrl = new URL("gopher://" + inputValue);
	                            } else {
	                                curUrl = new URL("http://" + inputValue);
	                            }
	                    }
	                }
	                            
	                webBrowser.setURL(curUrl);

	                // Update the address text field, statusbar, and toolbar info.
	                updateStatusInfo("Loading " + curUrl.toString() + " ......");

	            } catch (MalformedURLException mue) {
	                JOptionPane.showMessageDialog(this,
	                    "The given URL is not valid:" + inputValue, "Warning",
	                    JOptionPane.WARNING_MESSAGE);
	            }                
	        }
	    }

	    void jGoButton_actionPerformed(ActionEvent e) {
	        loadURL();
	    }

	    void jAddressTextField_actionPerformed(ActionEvent e) {
	        loadURL();
	    }

	    void jBackButton_actionPerformed(ActionEvent e) {
	        webBrowser.back();
	    }

	    void jForwardButton_actionPerformed(ActionEvent e) {
	        webBrowser.forward();
	    }

	    void jRefreshButton_actionPerformed(ActionEvent e) {
	        webBrowser.refresh();
	    }

	    void jStopButton_actionPerformed(ActionEvent e) {
	        webBrowser.stop();
	    }
	}


	class Browser_jAddressTextField_actionAdapter implements java.awt.event.ActionListener {
	    Browser adaptee;

	    Browser_jAddressTextField_actionAdapter(Browser adaptee) {
	        this.adaptee = adaptee;
	    }

	    public void actionPerformed(ActionEvent e) {
	        adaptee.jAddressTextField_actionPerformed(e);
	    }
	}


	class Browser_jBackButton_actionAdapter implements java.awt.event.ActionListener {
	    Browser adaptee;

	    Browser_jBackButton_actionAdapter(Browser adaptee) {
	        this.adaptee = adaptee;
	    }

	    public void actionPerformed(ActionEvent e) {
	        adaptee.jBackButton_actionPerformed(e);
	    }
	}


	class Browser_jForwardButton_actionAdapter implements java.awt.event.ActionListener {
	    Browser adaptee;

	    Browser_jForwardButton_actionAdapter(Browser adaptee) {
	        this.adaptee = adaptee;
	    }

	    public void actionPerformed(ActionEvent e) {
	        adaptee.jForwardButton_actionPerformed(e);
	    }
	}


	class Browser_jRefreshButton_actionAdapter implements java.awt.event.ActionListener {
	    Browser adaptee;

	    Browser_jRefreshButton_actionAdapter(Browser adaptee) {
	        this.adaptee = adaptee;
	    }

	    public void actionPerformed(ActionEvent e) {
	        adaptee.jRefreshButton_actionPerformed(e);
	    }
	}


	class Browser_jStopButton_actionAdapter implements java.awt.event.ActionListener {
	    Browser adaptee;

	    Browser_jStopButton_actionAdapter(Browser adaptee) {
	        this.adaptee = adaptee;
	    }

	    public void actionPerformed(ActionEvent e) {
	        adaptee.jStopButton_actionPerformed(e);
	    }
	}


	class Browser_jGoButton_actionAdapter implements java.awt.event.ActionListener {
	    Browser adaptee;

	    Browser_jGoButton_actionAdapter(Browser adaptee) {
	        this.adaptee = adaptee;
	    }

	    public void actionPerformed(ActionEvent e) {
	        adaptee.jGoButton_actionPerformed(e);
	    }
	}

	
}
